package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存访客数据
     * @param visitors
     */
    @Override
    public void save(Visitors visitors) {
        //对于同一个用户，一天之内只保存一次访客记录
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitorUserId").is(visitors.getVisitorUserId())
                .and("visitDate").is(visitors.getVisitDate()));
        //判断是否已经存在用户当天的访客记录
        boolean exists = mongoTemplate.exists(query, Visitors.class);
        //不存在则保存
        if (!exists){
            mongoTemplate.save(visitors);
        }
    }

    /**
     * 查询主页最近访客列表，显示在主页
     * @param userId
     * @param date
     * @return
     */
    @Override
    public List<Visitors> queryVisitorsList(Long userId, Long date) {
        Criteria criteria = Criteria.where("userId").is(userId).and("visitorUserId").ne(userId);
        if (date!=null){
            criteria.and("date").gt(date);
        }
        //将查询出来的数据按照时间降序排列，并只查询5条在主页显示
        Query query = Query.query(criteria).limit(5).with(Sort.by(Sort.Order.desc("date")));
        List<Visitors> visitors = mongoTemplate.find(query, Visitors.class);
        return visitors;
    }

    /**
     * 查询所有访客，并根据访问时间倒序排列
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryAllVisitorsList(Long userId) {
        List<Visitors> list = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId).and("visitorUserId").ne(userId))
                .with(Sort.by(Sort.Order.desc("visitDate")))
                .with(Sort.by(Sort.Order.desc("date"))), Visitors.class);

        return list;
    }
}
